#!/usr/bin/node

const SerialPort = require('serialport');

function usage() {
    console.error("Usage:");
    console.error('node terminal.js path');
    console.error('');
    console.error('Arguments:');
    console.error('  path: serial device path, for example: /dev/ttyUSB0');
    console.error('');
    
    process.exit();
}

if(process.argv.length <= 2) {
    usage();
}

var serialPath = process.argv[2];
var serialOptions = {
    autoOpen: false,
    baudRate: 1000000
}

var port = new SerialPort(serialPath, serialOptions);
port.open(port_on_open);

function port_on_open(err) {
    if(err) {
        console.error(err.message);
        process.exit();
    }
    
    var ain = 0;
    var ain_hi_valid = false;
    
    port.on('error', function (err) {
        console.error(err.message);
        process.exit(1);
    });
    
    port.on('data', function (data) {
      for(var i = 0; i < data.length; i++) {
          if((data[i] & 0xc0) == 0x80) {
              ain_hi_valid = true;
              ain = (data[i] & 0x3f) << 6;
          } else if((data[i] & 0xc0) == 0x40) {
              if(ain_hi_valid) {
                  ain |= data[i] & 0x3f;
                  console.log(ain);
              } else {
                  console.error('ERROR: Unexpected data order.');
              }
              ain_hi_valid = false;
          } else {
              console.error('ERROR: Unexpected data: %d.', data[i]);
              ain_hi_valid = false;
          }
      }
    });
    
    port.flush();
    port.write('eee', function () {
        setTimeout(function () {
            port.write('zzz', function () {
                setTimeout(function () {
                    port.write('ddd', function () {
                        process.exit();
                    });
                }, 2000);
            });
        }, 1000);
    });
}

